﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System.Diagnostics;
using System.Reflection;

namespace NeoPatterns.Patterns.UniformAccessor
{
    /// <summary>
    /// A member returned by uniform accessor is identified by its name and index (for lists)
    /// </summary>
    [DebuggerDisplay("MemberRef {Name}[{Index}]")]
    public class MemberRef
    {
        /// <summary>
        /// Member name (MemberInfo.Name)
        /// </summary>
        public string Name { get; private set; }
        /// <summary>
        /// Index value for lists, -1 for single values
        /// </summary>
        public int? Index { get; private set; }

        public override int GetHashCode()
        {
            return Name.GetHashCode() ^ Index.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var memberName = obj as MemberRef;
            if (memberName == null)
                return false;
            return Name == memberName.Name && Index == memberName.Index;
        }

        public MemberRef(string name, int? index)
        {
            Name = name;
            Index = index;
        }

        public MemberRef(string name)
            : this(name, null)
        {
        }

        public MemberRef(MemberInfo memberInfo)
            : this(memberInfo.Name)
        {
        }

        /// <summary>
        /// Casts a string to MemberRef
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static implicit operator MemberRef(string name)
        {
            return new MemberRef(name);
        }

        /// <summary>
        /// Casts a MemberInfo to MemberRef
        /// </summary>
        /// <param name="memberInfo"></param>
        /// <returns></returns>
        public static implicit operator MemberRef(MemberInfo memberInfo)
        {
            return new MemberRef(memberInfo);
        }
    }
}
